package cn.com.jtang.wedding.dao.impl;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.NotReadablePropertyException;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.jdbc.core.RowMapper;

import cn.com.jtang.wedding.jdbc.JdbcDao;
import cn.com.jtang.wedding.model.User;


public abstract class BaseDaoImpl {

	protected JdbcDao jdbcDao;
	protected String tableName;

	protected class ObjectMapper implements RowMapper {

		  public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			  return resultMapper(rs, rowNum);
		  }

	}

	public abstract Object resultMapper(ResultSet rs, int rowNum) throws SQLException;

	public abstract Map updateModelToMap(Object object);

	public abstract List insertModelToList(Object object);
	
	protected Object getObjectAttr(Object object, String attr) {
		String methodName = "get" + attr.substring(0, 1).toUpperCase()
				+ attr.substring(1);
		try {
			Method method = object.getClass().getMethod(methodName, null);
			return method.invoke(object, null);
		} catch (Exception ex) {
			throw new NotReadablePropertyException(Object.class, attr);
		}
	}

	protected void setObjectAttr(Object object, String attr, Class attrType,
			Object value) {
		String methodName = "set" + attr.substring(0, 1).toUpperCase()
				+ attr.substring(1);
		try {
			Method method = object.getClass().getMethod(methodName, attrType);
			method.invoke(object, value);
		} catch (Exception ex) {
			throw new NotWritablePropertyException(Object.class, attr);
		}
	}
	
	public String insert(Object object){
		List args = insertModelToList(object);
		int rows = jdbcDao.insert(this.tableName, args);
		if (rows > 0) {
			return "0";
		} else
			return "-1";
	}
	
	public Object queryById(Long id){
		
		return jdbcDao.queryById(this.tableName, id , new ObjectMapper());
		
	}
	
	public int updateById(Long id, Object object) {
		Map map = updateModelToMap(object);
		int rows = jdbcDao.updateById(this.tableName, map, id);
		return rows;
	}
	
	public int deleteById(Long id) {
		int rows = jdbcDao.deleteById(this.tableName, id);
		return rows;
	}
	
	public List queryAll(Map<String, Object> map, int start,int end, String... orderByStr){
		List objects = jdbcDao.
			queryAll(this.tableName, map, new ObjectMapper(), start, end, orderByStr);
		return objects;
	}
	
	public int getCount(Map<String,Object> map){
		return jdbcDao.getCount(tableName, map);
	}

	public JdbcDao getJdbcDao() {
		return jdbcDao;
	}

	public void setJdbcDao(JdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	
	
	
}
